import React, { memo, useEffect, useState } from "react";
import { useNavigate, useLocation, useRoutes, Link } from "react-router-dom";
import i18n from "i18next";
import {
  Avatar,
  Breadcrumb,
  Button,
  Drawer,
  message,
  Popover,
  Tag,
  Tooltip,
} from "antd";
import {
  AntDesignOutlined,
  ArrowLeftOutlined,
  BellOutlined,
  CloseOutlined,
  HomeOutlined,
  MenuOutlined,
  TranslationOutlined,
  UserOutlined,
} from "@ant-design/icons";
import INavbar from "@/components/home/navbar/navbar";
import HeaderCpn from "./header-cpn";
import { DownOutlined } from "@ant-design/icons";
import { Dropdown, Space, Divider } from "antd";
import type { MenuProps } from "antd";
import HomeHeaderWrapper from "./style";
import { useDispatch, useSelector } from "react-redux";
import {
  IDispatch,
  IStore,
  ResetSliceActions,
  SaveBreadCrumbActions,
} from "@/store";
import { useTranslation } from "react-i18next";
import { LogoutService } from "@/service";
import { SocketServer } from "@/App";
export default memo(() => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const _ = useLocation();
  const dispatch = useDispatch<IDispatch>();
  const [activeMember, setActiveMember] = useState([]);
  const [openMenu, setOpenMenu] = useState(false);
  const [breadcrumb, setBreadcrumb] = useState<any[]>([]);
  const store = useSelector((state: IStore) => state.user);
  const translate = (
    <div className="flex gap-2">
      <Button
        type={i18n.language == "zh" ? "primary" : "default"}
        onClick={() => {
          i18n.changeLanguage("zh");
          localStorage.setItem("wewin-language", "zh");
        }}
      >
        zh
      </Button>
      <Button
        type={i18n.language == "en" ? "primary" : "default"}
        onClick={() => {
          i18n.changeLanguage("en");
          localStorage.setItem("wewin-language", "en");
        }}
      >
        en
      </Button>
    </div>
  );
  const content = (
    <div className="flex gap-2">
      <Button
        onClick={() => {
          dispatch(SaveBreadCrumbActions([]));
          navigate("/home/index");
        }}
      >
        全部关闭
      </Button>
      <Button
        onClick={() => {
          dispatch(
            SaveBreadCrumbActions(
              store.breadcrumb.filter((item) => item.path == _.pathname)
            )
          );
        }}
      >
        其它关闭
      </Button>
    </div>
  );

  function gotoInfoClick() {
    if (_.pathname != "/home/info") {
      navigate("/home/info");
      const route = store.breadcrumb.find((item) => item.path == "/home/info");
      !route &&
        dispatch(
          SaveBreadCrumbActions([
            {
              path: "/home/info",
              name: "修改信息",
            },
            ...store.breadcrumb,
          ])
        );
    }
  }

  function handleLogoutClick() {
    LogoutService().then(async () => {
      await dispatch(ResetSliceActions());
      SocketServer?.close();
      message.success("退出登录成功! 跳转到登录页面中!");
      navigate("/login?" + _.pathname);
    });
  }
  useEffect(() => {
    if (store.menu) {
      const parent = store.menu.find((item) => {
        for (let i = 0; i < item.children.length; i++) {
          if (_.pathname == item.children[i].key) {
            return item;
          }
        }
      });
      let son = parent?.children.find((item: any) => item.key == _.pathname);
      setBreadcrumb([
        {
          path: "/home/index",
          name: "首页",
        },
        {
          path: parent?.children[0].key,
          name: parent?.label,
        },
        {
          path: son?.key,
          name: son?.label,
        },
      ]);
    }
  }, [_.pathname]);
  const items: MenuProps["items"] = [
    {
      key: "1",
      label: <div onClick={() => gotoInfoClick()}>主页</div>,
    },
    {
      key: "2",
      label: <div onClick={() => handleLogoutClick()}>退出登录</div>,
    },
  ];
  const menuStyle = {
    boxShadow: "none",
  };
  useEffect(() => {
    const arr = [];
    store.users.forEach((itemy) => {
      const item = store.activeNames.find((itemx) => itemy.user_name == itemx);
      if (item) {
        arr.push(itemy);
      }
    });
    // if (!arr.length) {
    //   handleLogoutClick()
    //   return
    // }
    setActiveMember(arr);
  }, [store]);
  function itemRender(item: any, params: any, items: any, paths: any) {
    const last = items.indexOf(item) === items.length - 1;
    return last ? (
      <span>{item.title}</span>
    ) : (
      <Link to={item.href}>{item.title}</Link>
    );
  }
  return (
    <HomeHeaderWrapper className="home-header">
      <HeaderCpn
        itemRender={itemRender}
        breadcrumb={breadcrumb}
        content={content}
      ></HeaderCpn>
      {/* 菜单展示组件 */}
      <MenuOutlined
        onClick={() => setOpenMenu(true)}
        className="sm:block lg:hidden ml-3"
      />
      <Drawer
        title={
          <div>
            LHJ - Admin Manager
          </div>
        }
        placement="left"
        width={300}
        className="test-dewa"
        closable={false}
        onClose={() => setOpenMenu(false)}
        open={openMenu}
        // key={placement}
      >
        <INavbar theme={false} collapsed={true}></INavbar>
      </Drawer>
      {/* 信息展示 */}
      <div className="flex items-center gap-1 relative">
        <Popover content={translate} title="">
          <Tag
            style={{
              fontSize: "16px",
              padding: "2px 10px",
              cursor: "pointer",
            }}
          >
            <TranslationOutlined />
          </Tag>
        </Popover>

        <BellOutlined />

        <Avatar.Group
          className="w-14"
          max={{
            count: 1,
            popover: {
              trigger: "hover",
            },
            style: {
              color: "#f56a00",
              backgroundColor: "#fde3cf",
              cursor: "pointer",
            },
          }}
        >
          {activeMember.reverse().map((item) => {
            return (
              <Tooltip key={item.id} title={item.user_name} placement="bottom">
                <Avatar src={item.avatar} />
              </Tooltip>
            );
          })}
        </Avatar.Group>

        {/*  */}

        <Dropdown
          arrow
          menu={{ items }}
          dropdownRender={(menu) => (
            <div>
              {React.cloneElement(menu as React.ReactElement, {
                style: menuStyle,
              })}
              <Divider style={{ margin: 0 }} />
            </div>
          )}
        >
          <span className="h-26">
            <Space className="h-10">
              <div className=" flex items-center justify-center gap-1">
                {store.user?.nick_name}
                <img
                  className="cursor-pointer w-7 h-7 rounded-full overflow-hidden mr-1"
                  onClick={() => gotoInfoClick()}
                  src={store.user?.avatar}
                  alt=""
                />
                {t("welcome")}!
              </div>
              <DownOutlined />
            </Space>
          </span>
        </Dropdown>
      </div>
    </HomeHeaderWrapper>
  );
});
